<!--
 * 生产退料管理页面
 -->
<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="searchForm" class="form-inline">
        <el-form-item label="退料单编号">
          <el-input v-model="searchForm.mateCode" placeholder="请输入退料单编号" clearable style="width: 180px;"></el-input>
        </el-form-item>
        <el-form-item label="退料单名称">
          <el-input v-model="searchForm.mateName" placeholder="请输入退料单名称" clearable style="width: 180px;"></el-input>
        </el-form-item>
        <el-form-item label="生产工单">
          <el-input v-model="searchForm.productionOrder" placeholder="请输入生产工单" clearable style="width: 180px;"></el-input>
        </el-form-item>
        <el-form-item label="退料类型">
          <el-select v-model="searchForm.mateType" placeholder="请选择退料类型" clearable style="width: 160px;">
            <el-option label="余料退料" value="余料退料"></el-option>
            <el-option label="测试退料" value="测试退料"></el-option>
            <el-option label="环料退料" value="环料退料"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getTableData">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button type="default" @click="handleReset">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 错误消息区域 -->
    <el-alert
      v-if="errorMessage"
      :title="errorMessage"
      type="error"
      @close="errorMessage = ''"
      show-icon
      :closable="true"
      style="margin-bottom: 15px;"
    ></el-alert>

    <!-- 按钮区域 -->
    <div class="table-operator">
      <el-button type="primary" @click="handleAdd" size="default">
        <el-icon><Plus /></el-icon> 新增
      </el-button>
      <el-button type="success" @click="handleEditSelected" size="default" :disabled="!selectedRow || selectedRow.documents !== 1">
        <el-icon><Edit /></el-icon> 修改
      </el-button>
     
    </div>

    <!-- 表格区域 -->
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
    >
      <el-table-column type="selection" width="45" align="center" />
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="mateCode" label="退料单编号" min-width="130" />
      <el-table-column prop="mateName" label="退料单名称" min-width="150" />
      <el-table-column prop="mateType" label="退料类型" min-width="90" />
      <el-table-column prop="productionOrder" label="生产工单" min-width="130" />
      <el-table-column prop="workstation" label="工作站" min-width="90" />
      <el-table-column prop="mateTime" label="退料日期" min-width="100" >
        <template #default="scope">
          {{ scope.row.mateTime && typeof scope.row.mateTime === 'string' ? scope.row.mateTime.substring(0,10) : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="documents" label="单据状态" min-width="90">
        <template #default="scope">
          <el-tag v-if="scope.row.documents == 1" type="info">草稿</el-tag>
          <el-tag v-else-if="scope.row.documents === 2" type="danger">已取消</el-tag>
          <el-tag v-else-if="scope.row.documents === 3" type="primary">待执行退料</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click.stop="handleEdit(scope.row)" v-if="scope.row.documents === 1">
            <el-icon><Edit /></el-icon> 修改
          </el-button>
          <el-button type="primary" link disabled v-else>
            <el-icon><Edit /></el-icon> 修改
          </el-button>
          <el-button type="primary" link @click.stop="handleExecute(scope.row)" v-if="scope.row.documents === 3">
            <el-icon><Check /></el-icon> 执行退料
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="paging.pageindex"
        :page-size="paging.pagesize"
        @update:current-page="paging.pageindex = $event"
        @update:page-size="paging.pagesize = $event"
        :page-sizes="[2, 4, 6, 8]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="paging.total"
      />
    </div>

    <!-- 添加/编辑弹框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editMode ? '修改生产退料单头' : '添加生产退料单头'"
      width="650px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      @closed="resetForm">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        style="max-height: 500px; overflow-y: auto;"
      >
        <el-form-item label="退料单编号" prop="mateCode">
          <el-input 
            v-model="formData.mateCode" 
            placeholder="请输入退料单编号" 
            :disabled="autoGenerateCode || editMode"
            style="width: 220px;"
          ></el-input>
          <el-switch
            v-model="autoGenerateCode"
            class="ml-2"
            style="margin-left: 10px;"
            inline-prompt
            active-text="自动生成"
            inactive-text="手动输入"
            :disabled="editMode"
          />
        </el-form-item>
        <el-form-item label="退料单名称" prop="mateName">
          <el-input v-model="formData.mateName" placeholder="请输入退料单名称" style="width: 450px;"></el-input>
        </el-form-item>
        <el-form-item label="退料类型" prop="mateType">
          <el-select v-model="formData.mateType" placeholder="请选择退料类型" style="width: 220px;">
            <el-option label="余料退料" value="余料退料"></el-option>
            <el-option label="测试退料" value="测试退料"></el-option>
            <el-option label="环料退料" value="环料退料"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生产工单" prop="productionOrder">
          <el-input 
            v-model="formData.productionOrder" 
            placeholder="请输入生产工单" 
            style="width: 220px;"
          >
            <template #append>
              <el-button @click="searchProductionOrder">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="工作站" prop="workstation">
          <el-input v-model="formData.workstation" placeholder="请输入工作站" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="退料日期" prop="mateTime">
          <el-date-picker
            v-model="formData.mateTime"
            type="date"
            placeholder="选择日期"
            style="width: 220px;"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入备注内容"
            :rows="3"
            style="width: 450px;"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" @click="submitForm">保 存</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 生产工单弹框 -->
    <el-dialog v-model="productionOrderDialogVisible" title="生产工单"  width="1200px" :close-on-click-modal="false" :destroy-on-close="true">
      <el-form :inline="true" :model="searchForm2" class="form-inline">
        <el-form-item label="工单编码" prop="workOrderCode">
          <el-input v-model="searchForm2.workOrderCode" placeholder="请输入工单编码" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="工单名称" prop="workOrderName">
          <el-input v-model="searchForm2.workOrderName" placeholder="请输入工单名称" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="产品编号" prop="productNumber">
          <el-input v-model="searchForm2.productNumber" placeholder="请输入产品编号" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
            <el-input v-model="searchForm2.productName" placeholder="请输入产品名称" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="客户名称" prop="clientName">
            <el-input v-model="searchForm2.clientName" placeholder="请输入客户名称" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getProductionOrderData">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button type="default" @click="handleReset">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
      <el-table  :data="productionOrderData" border style="width: 100%"
        @row-click="handleProductionOrderRowClick"
        highlight-current-row
        :row-key="row => row.workOrderCode">
        <el-table-column width="50" align="center">
          <template #default="scope">
            <el-radio 
              v-model="selectedWorkOrderCode" 
              :label="scope.row.workOrderCode" 
              @change="() => handleProductionOrderRowClick(scope.row)"
              class="custom-radio"
              ></el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="workOrderCode" label="工单编码" min-width="130" />
        <el-table-column prop="workOrderName" label="工单名称" min-width="130" />
        <el-table-column prop="workOrderSource" label="工单来源" min-width="130" />
        <el-table-column prop="productNumber" label="产品编号" min-width="130" /> 
        <el-table-column prop="productName" label="产品名称" min-width="130" />
        <el-table-column prop="specifications" label="规格型号" min-width="130" />
        <el-table-column prop="unit" label="单位" min-width="130" />
        <el-table-column prop="workOrderCount" label="工单数量" min-width="130" />
        <el-table-column prop="clientCode" label="客户编码" min-width="130" />
        <el-table-column prop="clientName" label="客户名称" min-width="130" />
        <el-table-column prop="needsDate" label="需求日期" min-width="130" />
      </el-table>
      <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="paging2.pageindex"
        :page-size="paging2.pagesize"
        :page-sizes="[2, 4, 6, 8]"
        @update:current-page="paging2.pageindex = $event"
        @update:page-size="paging2.pagesize = $event"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="paging2.total"/>
    </div>
    <template #footer>
        <el-button @click="productionOrderDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitProductionOrder">确 定</el-button>
    </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Upload, Check } from '@element-plus/icons-vue'
import http from '@/api/http'

// 检查http模块是否包含put方法，如果没有则添加一个简单实现
if (!http.put) {
  http.put = function(url, params, loading, config) {
    // 使用http.post方法，但在URL中添加_method=PUT参数
    const separator = url.includes('?') ? '&' : '?';
    const putUrl = `${url}${separator}_method=PUT`;
    return http.post(putUrl, params, loading, config);
  };
}

// 搜索表单
const searchForm = reactive({
    mateCode: '',
    mateName: '',
    mateType: '',
    productionOrder: ''
})

const paging = reactive({
    pageindex: 1,
    pagesize: 4,
    total: 0,
})

watch(paging, () => {
    getTableData()
})

// 表格数据
const tableData = ref([])
// 错误消息状态
const errorMessage = ref('')
// 选中的行
const selectedRow = ref(null)
// 编辑模式标志
const editMode = ref(false)
// 加载状态
const loading = ref(false)

// 行点击事件
const handleRowClick = (row) => {
  selectedRow.value = row
}

// 表格选择变化事件
const handleSelectionChange = (selection) => {
  selectedRow.value = selection.length > 0 ? selection[0] : null
}

// 获取表格数据
const getTableData = async () => {
    try {
        const loading = ElLoading.service({
            lock: true,
            text: '加载数据中...',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        
        try {
            await http.get(`api/Inventorytasks/QueryProductionmaterials?MateCode=${searchForm.mateCode}&MateName=${searchForm.mateName}&MateType=${searchForm.mateType}&ProductionOrder=${searchForm.productionOrder}&PageIndex=${paging.pageindex}&PageSize=${paging.pagesize}`).then(res => {
                console.log('获取表格数据响应:', res);
                if (res && res.rows) {
                    // 处理日期字段，确保它们是有效的字符串
                    tableData.value = res.rows.map(row => {
                        // 如果日期字段为null或undefined，设置为空字符串
                        if (!row.mateTime) {
                            row.mateTime = '';
                        }
                        return row;
                    });
                    paging.total = res.total || 0;
                } else {
                    tableData.value = [];
                    paging.total = 0;
                    console.error('返回数据格式不正确:', res);
                }
            });
        } finally {
            loading.close();
        }
    } catch (error) {
        console.error('获取表格数据出错:', error);
        ElMessage.error('获取数据失败，请稍后重试');
        tableData.value = [];
        paging.total = 0;
    }
}

const productionOrderDialogVisible = ref(false)
const searchProductionOrder=()=>{
    productionOrderDialogVisible.value = true
}
const searchForm2=reactive({
    workOrderCode: '',
    workOrderName: '',
    productNumber: '',
    productName: '',
    clientName: '',
})
const paging2 = reactive({
    pageindex: 1,
    pagesize: 4,
    total: 0,
})
watch(paging2, () => {
    getProductionOrderData()
})

const productionOrderData = ref([])
const getProductionOrderData = async () => {
    try {
        const loading = ElLoading.service({
            lock: true,
            text: '加载工单数据中...',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        
        try {
            await http.get(`api/Inventorytasks/QueryWorkorder?WorkOrderCode=${searchForm2.workOrderCode}&WorkOrderName=${searchForm2.workOrderName}&ProductNumber=${searchForm2.productNumber}&ProductName=${searchForm2.productName}&ClientName=${searchForm2.clientName}&PageIndex=${paging2.pageindex}&PageSize=${paging2.pagesize}`).then(res => {
                console.log('获取工单数据响应:', res);
                if (res && res.rows) {
                    // 处理日期字段，确保它们是有效的字符串
                    productionOrderData.value = res.rows.map(row => {
                        // 如果日期字段为null或undefined，设置为空字符串
                        if (!row.needsDate) {
                            row.needsDate = '';
                        }
                        return row;
                    });
                    paging2.total = res.total || 0;
                } else {
                    productionOrderData.value = [];
                    paging2.total = 0;
                    console.error('返回工单数据格式不正确:', res);
                }
            });
        } finally {
            loading.close();
        }
    } catch (error) {
        console.error('获取工单数据出错:', error);
        ElMessage.error('获取工单数据失败，请稍后重试');
        productionOrderData.value = [];
        paging2.total = 0;
    }
}

// 选中的生产工单
const selectedProductionOrder = ref(null)
const selectedWorkOrderCode = ref('')
// 行点击事件
const handleProductionOrderRowClick = (row) => {
    selectedProductionOrder.value = row
    selectedWorkOrderCode.value = row.workOrderCode
}
// 重置生产工单搜索表单
const handleReset = () => {
    if (searchForm2.workOrderCode || searchForm2.workOrderName || searchForm2.productNumber || searchForm2.productName || searchForm2.clientName) {
        // 重置工单搜索条件
        searchForm2.workOrderCode = '';
        searchForm2.workOrderName = '';
        searchForm2.productNumber = '';
        searchForm2.productName = '';
        searchForm2.clientName = '';
        // 重新获取工单数据
        getProductionOrderData();
    } else {
        // 重置主页面搜索条件
        searchForm.mateCode = '';
        searchForm.mateName = '';
        searchForm.mateType = '';
        searchForm.productionOrder = '';
        // 重新获取表格数据
        getTableData();
    }
}
// 确认选择工单
const submitProductionOrder = () => {
    if (!selectedProductionOrder.value) {
        ElMessage.warning('请选择一条工单记录')
        return
    }
    // 将选中的工单信息填充到表单
    formData.productionOrder = selectedProductionOrder.value.workOrderCode || ''
    
    // 可以同时更新其他相关字段，例如工作站等
    // formData.workstation = selectedProductionOrder.value.workstation || ''
    
    // 关闭对话框
    productionOrderDialogVisible.value = false
    
    // 提示用户选择成功
    ElMessage.success('工单选择成功')
}

// 弹框相关
const dialogVisible = ref(false)
const formRef = ref(null)
const formData = reactive({
    id: '',
    mateCode: '',
    mateName: '',
    mateType: '',
    productionOrder: '',
    workstation: '',
    mateTime: '',
    documents: 1,
    remark: '',
})
// 表单验证规则
const rules = reactive({
    mateCode: [
        { required: true, message: '请输入退料单编号', trigger: 'blur' }
    ],
    mateName: [
        { required: true, message: '请输入退料单名称', trigger: 'blur' }
    ],
    mateType: [
        { required: true, message: '请选择退料类型', trigger: 'change' }
    ],
    productionOrder: [
        { required: true, message: '请输入生产工单', trigger: 'blur' }
    ],
    mateTime: [
        { required: true, message: '请选择退料日期', trigger: 'change' }
    ]
})
const autoGenerateCode = ref(true)
// 监听自动生成编号开关
watch(autoGenerateCode, (newVal) => {
    if (newVal) {
        formData.mateCode = generateMateCode()
    } else {
        formData.mateCode = ''
    }
})
// 生成退料单编号
const generateMateCode = () => {
    return 'MO' + new Date().getTime().toString().slice(-8)
}
// 新增
const handleAdd =  () => {
    // 重置表单
    Object.keys(formData).forEach(key => {
        formData[key] = '';
    });
    formData.documents = 1;
    
    editMode.value = false;
    dialogVisible.value = true;
    autoGenerateCode.value = true;  
    // 自动生成退料单编号
    if (autoGenerateCode.value) {
        formData.mateCode = generateMateCode();
    }
    // 设置当前日期
    const currentDate = new Date().toISOString().split('T')[0];
    formData.mateTime = currentDate;
    formData.createDate = currentDate;
}

// 重置表单
const resetForm = () => {
    // 清空表单数据
    Object.keys(formData).forEach(key => {
        formData[key] = '';
    });
    // 重置编辑模式
    editMode.value = false;
    // 重置自动生成编号
    autoGenerateCode.value = true;
    // 清空错误消息
    errorMessage.value = '';
    // 重置表单验证
    if (formRef.value) {
        formRef.value.resetFields();
    }
    console.log('表单已重置');
}

// 取消表单
const cancelForm = () => {
    // 检查表单是否有修改
    const formChanged = Object.keys(formData).some(key => formData[key] !== '');
    
    if (formChanged) {
        ElMessageBox.confirm(
            '表单数据已修改，确定要取消吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            dialogVisible.value = false;
        }).catch(() => {
            // 用户取消关闭
        });
    } else {
        // 直接关闭
        dialogVisible.value = false;
    }
}

// 通过表格行修改
const handleEdit = async (row) => {
    try {
        // 先设置加载状态
        loading.value = true;
        
        // 检查记录是否有效
        if (!row || !row.id) {
            ElMessage.error('无效的记录数据');
            loading.value = false;
            return;
        }
        
        // 设置编辑模式
        editMode.value = true;
        
        // 清空表单数据
        Object.keys(formData).forEach(key => {
            formData[key] = '';
        });
        
        // 直接使用表格行数据
        formData.id = row.id;
        formData.mateCode = row.mateCode || '';
        formData.mateName = row.mateName || '';
        formData.mateType = row.mateType || '';
        formData.productionOrder = row.productionOrder || '';
        formData.workstation = row.workstation || '';
        formData.mateTime = row.mateTime ? (typeof row.mateTime === 'string' ? row.mateTime.substring(0, 10) : row.mateTime) : '';
        formData.documents = row.documents;
        formData.remark = row.remark || '';
        
        console.log('编辑表单数据:', formData);
        
        // 打开对话框
        dialogVisible.value = true;
        autoGenerateCode.value = true;  // 编辑模式下应该禁止修改编号
        
    } catch (error) {
        console.error('准备编辑表单出错:', error);
        ElMessage.error('准备编辑表单失败: ' + (error.message || String(error)));
    } finally {
        loading.value = false;
    }
}

// 通过选中行修改
const handleEditSelected = () => {
    if (!selectedRow.value) {
        ElMessage.warning('请先选择要修改的记录');
        return;
    }
    
    if (selectedRow.value.documents !== 1) {
        ElMessage.warning('只能修改草稿状态的记录');
        return;
    }
    
    handleEdit(selectedRow.value);
}

const submitForm = async () => {
  try {
    // 表单验证
    await formRef.value.validate();
    
    // 确保所有必要字段都有值
    if (!formData.mateCode || !formData.mateName || !formData.mateType || !formData.productionOrder || !formData.mateTime) {
      ElMessage.error('请填写所有必填字段');
      return;
    }
    
    // 编辑模式必须有ID
    if (editMode.value && !formData.id) {
      ElMessage.error('修改记录时ID不能为空');
      errorMessage.value = '修改记录时ID不能为空，请重新选择记录';
      return;
    }
    
    // 创建一个新对象，尝试更严格的数据格式
    const submitData = {
      mateCode: formData.mateCode.trim(),
      mateName: formData.mateName.trim(),
      mateType: formData.mateType.trim(),
      productionOrder: formData.productionOrder.trim(),
      workstation: (formData.workstation || '').trim(),
      mateTime: formData.mateTime,
      documents: 1, // 重新使用数字类型
      remark: (formData.remark || '').trim()
    };
    
    // 如果是编辑模式，需要添加id
    if (editMode.value && formData.id) {
      submitData.id = Number(formData.id); // 尝试转换为数字类型
    }
    
    // 清空错误消息
    errorMessage.value = '';
    
   
    
    const loading = ElLoading.service({
      lock: true,
      text: `${editMode.value ? '修改' : '新增'}数据中...`,
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    try {
      let res;
      
      if (editMode.value) {
        // 修改模式 - 改为使用服务端API      
        // 确保ID正确设置
        const updateData = { ...submitData, Id: submitData.id };
        // 尝试使用规范的API命名"UpdateProductionmaterials"
        res = await http.post('api/Inventorytasks/UpdProductionmaterials', updateData, true, {
          timeout: 15000 // 15秒超时
        });
      } 
      
      // 更宽松的成功判断条件
      if (
        (res && res.code == 200) || // 标准成功响应
        (res && res.status) ||      // 有status字段且为真
        (res && res.success) ||     // 有success字段且为真
        (res && res.data) ||        // 有data字段
        (res && !res.error)         // 没有error字段或error为假
      ) {
        ElMessage.success(editMode.value ? '修改成功' : '新增成功3');
        
        // 稍后验证数据是否真的保存成功
        setTimeout(() => {
          getTableData().then(() => {
            // 在表格数据刷新后检查修改是否真的被保存
            if (editMode.value) {
              tableData.value.find(item => item.id === submitData.id);   
            }
          });
        }, 1000);
        
        dialogVisible.value = false;
        // 重置选中行
        selectedRow.value = null;
        // 重置表单
        resetForm();
        return;
      }
      
      // 如果没有明确的失败标志，也认为是成功
      if (res && typeof res === 'object' && Object.keys(res).length > 0 && !res.message && !res.error) {
        ElMessage.success('数据已成功提交到服务器');
        
        // 稍后验证数据是否真的保存成功
        setTimeout(() => {
          getTableData().then(() => {
            // 在表格数据刷新后检查修改是否真的被保存
            if (editMode.value) {
              const updatedItem = tableData.value.find(item => item.id === submitData.id);
              if (updatedItem) {
                const fieldsMatch = (
                  updatedItem.mateName === submitData.mateName &&
                  updatedItem.mateType === submitData.mateType
                );
                
                if (fieldsMatch) {
                  console.log('验证成功：数据已正确保存到服务器');
                } else {
                  console.warn('数据可能未完全保存，本地显示的数据与提交的数据不一致');
                  ElMessage.warning('提示：数据可能未完全保存，请检查并可能需要重新提交');
                }
              } else {
                console.warn('无法在刷新后的表格中找到修改的记录');
              }
            }
          });
        }, 1000);
        
        dialogVisible.value = false;
        // 重置选中行
        selectedRow.value = null;
        // 重置表单
        resetForm();
        return;
      }
      
      // 显示详细的错误信息
      const errorMsg = (res && res.message) ? res.message : '保存失败，请检查数据格式';
      ElMessage.error(errorMsg);
      errorMessage.value = errorMsg;
      console.error('API错误响应:', res);
      
      // 如果修改保存失败，提供备选方案
      if (editMode.value) {
        ElMessageBox.confirm(
          '服务器保存失败，是否尝试在本地临时保存修改？（注意：刷新页面后修改会丢失）',
          '保存失败',
          {
            confirmButtonText: '临时保存在本地',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          try {
            // 找到当前表格中的对应项
            const index = tableData.value.findIndex(item => item.id === submitData.id);
            
            if (index !== -1) {
              // 更新本地数据
              tableData.value[index] = { ...tableData.value[index], ...submitData };
              console.log('已在本地表格中临时更新数据');
              
              // 提示用户已临时修改成功，但需要注意
              ElMessage({
                message: '修改已临时保存在本地（警告：刷新页面后修改会丢失）',
                type: 'warning',
                duration: 8000 // 延长显示时间
              });
              
              // 关闭对话框
              dialogVisible.value = false;
              // 重置表单
              resetForm();
            } else {
              ElMessage.error('找不到要修改的记录，临时保存也失败了');
            }
          } catch (e) {
            console.error('临时保存失败', e);
            ElMessage.error('临时保存也失败了: ' + (e.message || String(e)));
          }
        }).catch(() => {
          // 用户取消临时保存
          ElMessage.info('已取消临时保存');
        });
      }
    } catch (error) {
      console.error('API调用失败:', error);
      
      let errorMsg = '提交数据时出错';
      
      // 解析错误信息
      if (error.response) {
        // 服务器返回错误状态码
        if (error.response.status === 404) {
          errorMsg = 'API接口不存在，请联系管理员';
        } else if (error.response.status === 500) {
          errorMsg = '服务器内部错误';
        } else {
          errorMsg = `服务器返回错误: ${error.response.status}`;
        }
      } else if (error.request) {
        // 请求已发送但没有收到响应
        errorMsg = '服务器无响应，请检查网络连接';
      } else if (error.message) {
        // 设置请求时发生错误
        errorMsg = error.message;
      }
      
      // 输出详细错误信息到控制台
      console.error('详细错误信息:', errorMsg, error);
      
      ElMessage.error(errorMsg);
      errorMessage.value = errorMsg;
    } finally {
      loading.close();
      // 无论成功还是失败，都刷新表格数据
      getTableData();
    }
  } catch (error) {
    console.error('表单验证出错:', error);
    ElMessage.error('表单验证失败: ' + (error.message || String(error)));
  }
}

// 执行退料
const handleExecute = (row) => {
    ElMessageBox.confirm(
        '确定要执行该退料单吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        try {
            const loading = ElLoading.service({
                lock: true,
                text: '处理中...',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            
            try {
                const res = await http.post(`api/Inventorytasks/ExecuteProductionmaterials?id=${row.id}`, {}, true);
                console.log('执行退料响应:', res);
                
                if (res && (res.code == 200 || res.status || res.success)) {
                    ElMessage.success('执行退料成功');
                } else {
                    const errorMsg = (res && res.message) ? res.message : '执行退料失败';
                    ElMessage.error(errorMsg);
                    errorMessage.value = errorMsg;
                }
            } finally {
                loading.close();
                // 刷新表格数据
                getTableData();
            }
        } catch (error) {
            console.error('执行退料出错:', error);
            ElMessage.error('执行退料失败: ' + (error.message || String(error)));
            // 刷新表格数据
            getTableData();
        }
    }).catch(() => {
        // 用户取消操作
    });
}

onMounted(() => {
    getTableData()
    getProductionOrderData()
})
</script>

<style scoped>
.app-container {
  padding: 15px;
  width: 100%;
  box-sizing: border-box;
}

/* 自定义单选框样式，移除文字 */
.custom-radio :deep(.el-radio__label) {
  display: none;
}

.filter-container {
  margin-bottom: 15px;
  padding: 15px 10px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.form-inline {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.form-inline .el-form-item {
  margin-right: 10px;
  margin-bottom: 10px;
}

.table-operator {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.table-operator .el-button {
  margin-right: 10px;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.el-tag {
  margin-right: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.empty-data-message {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30px 0;
}
</style>
